package com.android.love.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebIconDatabase;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;


import com.android.love.R;

import com.android.love.util.ActivityUtil;
import com.android.love.util.ApkUtil;

import com.android.love.util.LogUtil;
import com.android.love.util.StringsUtil;


import com.android.love.web.ApplicationUtils;
import com.android.love.web.Controller;
import com.android.love.web.CustomWebView;
import com.android.love.web.CustomWebViewClient;
import com.android.love.web.DownloadItem;
import com.android.love.web.EventConstants;
import com.android.love.web.EventController;
import com.android.love.web.IDownloadEventsListener;
import com.android.love.web.UrlUtils;


public class MyWebViewActivity extends BaseActivity implements IDownloadEventsListener,CustomWebViewClient.CustomWebViewClientLister,OnClickListener {

    public static final String TAG = "WebActivity";

    private String path;

    private Dialog dialog;

    public static MyWebViewActivity INSTANCE = null;

    protected LayoutInflater mInflater = null;

    private CustomWebView mCurrentWebView;

    private List<CustomWebView> mWebViews;

    private ViewFlipper mViewFlipper;

//    private ProgressBar mProgressBar;

    private ValueCallback<Uri> mUploadMessage;

    private Bitmap mDefaultVideoPoster = null;

    private View mVideoProgressView = null;

    private View mCustomView;

    private FrameLayout mFullscreenContainer;

    private WebChromeClient.CustomViewCallback mCustomViewCallback;

    // private static final int OPEN_DOWNLOADS_ACTIVITY = 1;
    private static final int OPEN_FILE_CHOOSER_ACTIVITY = 2;

    protected static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);


    // private Dialog dialog2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityUtil.setScreenVertical(this);
		ActivityUtil.hideTitleBar(this);
        setContentView( R.layout.web_love);
        INSTANCE = this;
        EventController.getInstance().addDownloadListener(this);
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        buildComponents();
        mViewFlipper.removeAllViews();
        Intent intent = getIntent();
        path = intent.getStringExtra("path");
        if (path == null) {
            finish();
            return;
        }
        int type=intent.getIntExtra("type", 0);
        if(type==1){
        	finder.textView(R.id.top_title).setText("服务条款");
        }else if(type==2){
        	
        	finder.textView(R.id.top_title).setText("负责声明");
        }
        LogUtil.i(TAG, "path---" + path);
        addTab();
        navigateToUrl(path);
    }


    @Override
    protected void onDestroy() {
        if (mCurrentWebView != null) {
            mCurrentWebView.clearCache(true);
            mCurrentWebView.destroy();
            mCurrentWebView = null;
            // Constant.PURCHASE_FROM_MAIN=true;
            EventController.getInstance().removeDownloadListener(this);
        }
        super.onDestroy();
    }

    /**
     * 跳转到所给url
     *
     * @param url The url.
     */
    private void navigateToUrl(String url) {

        LogUtil.i(TAG, "url:" + url);

        if ((url != null) && (url.length() > 0)) {

            if (UrlUtils.isUrl(url)) {
                url = UrlUtils.checkUrl(url);
            }
            mCurrentWebView.loadUrl(url);
        }
    }

    /**
     * 添加一个新页面
     */
    private void addTab() {
        addTab(-1);
    }

    /**
     * 添加一个新页面
     *
     * @param parentIndex 新页面的index
     */
    private void addTab(int parentIndex) {

        RelativeLayout view = (RelativeLayout) mInflater.inflate(R.layout.webview, mViewFlipper, false);

        mCurrentWebView = (CustomWebView) view.findViewById(R.id.webview);

        initializeCurrentWebView();

        synchronized (mViewFlipper) {
            if (parentIndex != -1) {
                mWebViews.add(parentIndex + 1, mCurrentWebView);
                mViewFlipper.addView(view, parentIndex + 1);
            } else {
                mWebViews.add(mCurrentWebView);
                mViewFlipper.addView(view);
            }
            mViewFlipper.setDisplayedChild(mViewFlipper.indexOfChild(view));
        }
//        mProgressBar.setProgress(mCurrentWebView.getProgress());
        updateWebBar();
    }

    /**
     * 初始化新创建的WebView.
     */
    private void initializeCurrentWebView() {
        CustomWebViewClient  client=  new CustomWebViewClient(this);
        client.setCustomWebViewClientLister(this);
        mCurrentWebView.setWebViewClient(client);
        mCurrentWebView.setDownloadListener(new DownloadListener() {

            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                doDownloadStart(url, userAgent, contentDisposition, mimetype, contentLength);
            }

        });

        mCurrentWebView.setWebChromeClient(new WebChromeClient() {

            @SuppressWarnings("unused")
            // This is an undocumented method, it _is_ used, whatever Eclipse
            // may think :)
            // Used to show a file chooser dialog.
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                LogUtil.i(TAG, "mCurrentWebView---openFileChooser");
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                MyWebViewActivity.this.startActivityForResult(
                        Intent.createChooser(i, MyWebViewActivity.this.getString(R.string.Main_FileChooserPrompt)),
                        OPEN_FILE_CHOOSER_ACTIVITY);
            }

            @SuppressWarnings("unused")
            // This is an undocumented method, it _is_ used, whatever Eclipse
            // may think :)
            // Used to show a file chooser dialog.
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                LogUtil.i(TAG, "mCurrentWebView---openFileChooser2");
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                MyWebViewActivity.this.startActivityForResult(
                        Intent.createChooser(i, MyWebViewActivity.this.getString(R.string.Main_FileChooserPrompt)),
                        OPEN_FILE_CHOOSER_ACTIVITY);
            }

            @Override
            public Bitmap getDefaultVideoPoster() {
                LogUtil.i(TAG, "mCurrentWebView---getDefaultVideoPoster");
                if (mDefaultVideoPoster == null) {
                    mDefaultVideoPoster =
                            BitmapFactory.decodeResource(MyWebViewActivity.this.getResources(), R.drawable.default_video_poster);
                }

                return mDefaultVideoPoster;
            }

            @Override
            public View getVideoLoadingProgressView() {
                LogUtil.i(TAG, "mCurrentWebView---getVideoLoadingProgressView");
                if (mVideoProgressView == null) {
                    LayoutInflater inflater = LayoutInflater.from(MyWebViewActivity.this);
                    mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
                }

                return mVideoProgressView;
            }

            public void onShowCustomView(View view, CustomViewCallback callback) {
                LogUtil.i(TAG, "mCurrentWebView---onShowCustomView");
                showCustomView(view, callback);
            }

            @Override
            public void onHideCustomView() {
                LogUtil.i(TAG, "mCurrentWebView---onHideCustomView");
                hideCustomView();
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                ((CustomWebView) view).setProgress(newProgress);
//                mProgressBar.setProgress(mCurrentWebView.getProgress());
            }

            @Override
            public void onReceivedIcon(WebView view, Bitmap icon) {

                LogUtil.i(TAG, "mCurrentWebView---onReceivedIcon");
                super.onReceivedIcon(view, icon);
            }

            @Override
            public boolean onCreateWindow(WebView view, final boolean dialog, final boolean userGesture, final Message resultMsg) {
                LogUtil.i(TAG, "mCurrentWebView---onCreateWindow");
                WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;

                addTab(mViewFlipper.getDisplayedChild());

                transport.setWebView(mCurrentWebView);
                resultMsg.sendToTarget();

                return true;
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                LogUtil.i(TAG, "mCurrentWebView---onReceivedTitle");
                super.onReceivedTitle(view, title);
            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                LogUtil.i(TAG, "mCurrentWebView---onJsAlert");
                new AlertDialog.Builder(MyWebViewActivity.this).setTitle(R.string.Commons_JavaScriptDialog).setMessage(message)
                        .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                result.confirm();
                            }
                        }).setCancelable(false).create().show();

                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                LogUtil.i(TAG, "mCurrentWebView---onJsConfirm");
                new AlertDialog.Builder(MyWebViewActivity.this).setTitle(R.string.Commons_JavaScriptDialog).setMessage(message)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {
                                result.confirm();
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        result.cancel();
                    }
                }).create().show();

                return true;
            }

            @Override
            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) {
                LogUtil.i(TAG, "mCurrentWebView---onJsPrompt");
                final LayoutInflater factory = LayoutInflater.from(MyWebViewActivity.this);
                final View v = factory.inflate(R.layout.javascript_prompt_dialog, null);
                ((TextView) v.findViewById(R.id.JavaScriptPromptMessage)).setText(message);
                ((EditText) v.findViewById(R.id.JavaScriptPromptInput)).setText(defaultValue);

                new AlertDialog.Builder(MyWebViewActivity.this).setTitle(R.string.Commons_JavaScriptDialog).setView(v)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int whichButton) {
                                String value = ((EditText) v.findViewById(R.id.JavaScriptPromptInput)).getText().toString();
                                result.confirm(value);
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        result.cancel();
                    }
                }).setOnCancelListener(new DialogInterface.OnCancelListener() {

                    public void onCancel(DialogInterface dialog) {
                        result.cancel();
                    }
                }).show();

                return true;

            }

        });
    }

    /**
     * 初始化下载器，检查SD卡并开启下载线程
     *
     * @param url                The url to download.
     * @param userAgent          The user agent.
     * @param contentDisposition The content disposition.
     * @param mimetype           The mime type.
     * @param contentLength      The content length.
     */
    private void doDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {

        if (ApplicationUtils.checkCardState(this, true)) {
            DownloadItem item = new DownloadItem(this, url);
            Controller.getInstance().addToDownload(item);
            item.startDownload();

            Toast.makeText(this, getString(R.string.Main_DownloadStartedMsg), Toast.LENGTH_SHORT).show();
        }
    }

    private void showCustomView(View view, WebChromeClient.CustomViewCallback callback) {
        // if a view already exists then immediately terminate the new one
        if (mCustomView != null) {
            callback.onCustomViewHidden();
            return;
        }

        MyWebViewActivity.this.getWindow().getDecorView();
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        mFullscreenContainer = new FullscreenHolder(MyWebViewActivity.this);
        mFullscreenContainer.addView(view, COVER_SCREEN_PARAMS);
        decor.addView(mFullscreenContainer, COVER_SCREEN_PARAMS);
        mCustomView = view;
        mCustomViewCallback = callback;

    }

    private void hideCustomView() {
        if (mCustomView == null)
            return;
        FrameLayout decor = (FrameLayout) getWindow().getDecorView();
        decor.removeView(mFullscreenContainer);
        mFullscreenContainer = null;
        mCustomView = null;
        mCustomViewCallback.onCustomViewHidden();
    }

    /**
     * 创建UI
     */
    private void buildComponents() {
        mWebViews = new ArrayList<CustomWebView>();
        Controller.getInstance().setWebViewList(mWebViews);
        mViewFlipper = finder.find(R.id.ViewFlipper);
//        mProgressBar = finder.find(R.id.progressWebLoad);
//        mProgressBar.setVisibility(View.GONE);
        finder.find(R.id.ll_right).setVisibility(View.GONE);
//        finder.find(R.id.ll_right).setVisibility(View.GONE);
        finder.find(R.id.iv_top_meinv).setOnClickListener(this);
//        mProgressBar.setMax(100);


    }

    @Override
    public void onDownloadEvent(String event, Object data) {
        if (event.equals(EventConstants.EVT_DOWNLOAD_ON_FINISHED)) {

            DownloadItem item = (DownloadItem) data;

            if (item.getErrorMessage() == null) {
                Toast.makeText(this, getString(R.string.Main_DownloadFinishedMsg), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, getString(R.string.Main_DownloadErrorMsg, item.getErrorMessage()), Toast.LENGTH_SHORT).show();
            }
        }
    }

    static class FullscreenHolder extends FrameLayout {

        public FullscreenHolder(Context ctx) {
            super(ctx);
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black));
        }

        @Override
        public boolean onTouchEvent(MotionEvent evt) {
            return true;
        }

    }

    @Override
    protected void onPause() {
        LogUtil.i(TAG, "onPause");
        if (mCurrentWebView != null)
            mCurrentWebView.doOnPause();
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (mCurrentWebView != null)
            mCurrentWebView.doOnResume();

        super.onResume();
    }
    @Override
    public void onPageFinished(String url) {
        LogUtil.i(TAG, "mCurrentWebView---onPageFinished");


        updateWebBar();


//        mProgressBar.setProgress(mCurrentWebView.getProgress());


        WebIconDatabase.getInstance().retainIconForPageUrl(mCurrentWebView.getUrl());

    }
    @Override
    public void onPageStarted(String url) {
        LogUtil.i(TAG, "mCurrentWebView---onPageStarted");

//        mProgressBar.setVisibility(View.VISIBLE);

    }
    @Override
    public void onUrlLoading(String url) {

    }
    @Override
    public void onMailTo(String url) {
        Intent sendMail = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(sendMail);
    }
    @Override
    public void onExternalApplicationUrl(String url) {
        try {

            Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(i);


        } catch (Exception e) {
            String message = String.format(getString(R.string.Main_VndErrorMessage), url);

            new AlertDialog.Builder(this).setTitle(R.string.Main_VndErrorTitle).setMessage(message)
                    .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                        }
                    }).setCancelable(true).create().show();
        }

    }

//    public void setHttpAuthUsernamePassword(String host, String realm, String username, String password) {
//        mCurrentWebView.setHttpAuthUsernamePassword(host, realm, username, password);
//    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                LogUtil.i(TAG, "-----11");
                if (mCustomView != null) {
                    LogUtil.i(TAG, "-----22");
                    hideCustomView();
                } else {
                    // LogUtil.i(TAG, "url---" + mCurrentWebView.getUrl());
                    // LogUtil.i(TAG, "firstUrl---" + firstUrl);
                    LogUtil.i(TAG, "-----33");
                    if (mCurrentWebView.canGoBack() ) {
                        LogUtil.i(TAG, "-----44");

                        mCurrentWebView.goBack();
                    } else {
                        return super.onKeyDown(keyCode, event);
                    }
                }
                return true;
            default:
                return super.onKeyDown(keyCode, event);
        }
    }




    private void updateWebBar() {
        // if(mCurrentWebView.canGoBack()) {
        // if(mCurrentWebView.getUrl().equals(firstUrl)) {
        // iv_web_back.setImageResource(R.drawable.web_first);
        // } else {
        // iv_web_back.setImageResource(R.drawable.web_boy_back);
        // }
        // } else {
        // iv_web_back.setImageResource(R.drawable.web_first);
        // }
        // if(mCurrentWebView.canGoForward()) {
        // iv_web_forward.setImageResource(R.drawable.web_forward);
        // } else {
        // iv_web_forward.setImageResource(R.drawable.web_last);
        // }
    }



    @Override
    protected void onStop() {
        LogUtil.i(TAG, "onStop");

        super.onStop();
    }


    @Override
    public void onReceivedError(String failingUrl) {

        LogUtil.i(TAG, "failingUrl---" + failingUrl);
        // baseHandler.sendEmptyMessage(Constant.LOADING_DISMISS);
        if (dialog != null) {
            dialog.cancel();
            dialog = null;
        }

    }


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_top_meinv:
			if(mCurrentWebView.canGoBack()){
				mCurrentWebView.goBack();
			}else{
				finish(true);
			}
			
			break;

		default:
			break;
		}
	}


}
